// 首页
var app = getApp();
const recorderManager = wx.getRecorderManager();//录音管理
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // page: 1,
    // 左右滑动
    currentTab: 0,

    reset: 0,
    starplay: true,
    onspeak: true,
    state: 0,
    // 提示
    shadow: true,
    terms: true,//条款
    sensitive: true,//敏感
    sensitive_text: '',//敏感提示

    gift: false,
    limit_text: false,
    switchs:0,//是否显示在幸运池
    // 口令
    //  prize_money  当前小程序剩余的余额
    //  prize_src  用户输入的赏金金额
    //  duty  服务费
    //  formalities_momey  加上服务费的总金额
    //  pay_money  用户还需要微信支付的余额
    //  prize_num  数量
    mouth: { text: '', prize_money: '0.00', prize_src: '0.00', duty: '0.00', formalities_momey: '0.00', pay_money: '0.00', prize_num: '0', },
    bounty_value: '',
  },

  /*** 点击tab切换***/
  swichNav: function (e) {
    this.setData({
      currentTab: e.target.dataset.current,
      switchs: false,
      bounty_value:'',
      state:0,
      'mouth.pay_money':'',
      'mouth.duty':'',
    });
    // that.onLoad();
  },
  /*** 滑动切换tab***/
  bindChange: function (e) {
    this.setData({
      currentTab: e.detail.current,
      switchs: false,
      bounty_value: '',
      state: 0,
      'mouth.pay_money': '',
      'mouth.duty': '',
    });
    console.log(this.data.switchs);
    // that.onLoad();
  },

  // 是否在共享区显示
  switch2Change: function (e) {
    this.setData({ switchs: e.detail.value})
  },

  //录音
  touchdown: function (e) {
    console.log('手指按住');
    var that = this;
    that.setData({ onspeak: false, })
    //录音start
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    const options = {
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 72000,
      format: 'mp3',
      frameSize: 50
    }

    recorderManager.start(options);
    //end
  },
  touchup: function (e) {
    console.log('手指放开');
    var that = this;
    that.setData({ onspeak: true, reset: 1 })
    //录音停止
    recorderManager.stop((res) => { });
    //录音停止事件
    recorderManager.onStop((res) => {
      console.log(res.tempFilePath);
      that.setData({ tempFilePath: res.tempFilePath, duration: parseInt(res.duration / 1000), });
    })
  },
  // 录音播放
  gotoPlay: function () {
    var that = this;
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = true
    innerAudioContext.src = that.data.tempFilePath;
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
      that.setData({ starplay: false, })
    })

    innerAudioContext.onEnded((res) => {
      console.log('播放结束')
      that.setData({ starplay: true, })
    })
  },

  paying: function () {
    this.setData({
      shadow: false,
      terms: false,//条款
    })
  },
  know: function () {
    var that = this;
    that.setData({
      shadow: true,
      terms: true,//条款
      sensitive: true,//敏感
    })
  },
  //用户输入口令
  text_input: function (e) {
    var that = this;
    var value = e.detail.value;
    if (value.length == 20) {
      that.setData({ limit_text: true, });
      setTimeout(function () { that.setData({ limit_text: false, }); }, 2000)
    }
  },
  //用户输入金额
  money_input: function (e) {
    var that = this;
    var value = e.detail.value;
    if (value != '') {
      if (parseFloat(value) < 0) {
        that.setData({ gift: true, });
        setTimeout(function () { that.setData({ gift: false, }); }, 2000)
      } else {
        var num = parseFloat(value) * 0.02;//服务费
        var nums =  parseFloat(value);//需支付的总金额（包含服务费）
        //判断按钮显示的文案
        var state = 0;
        if (nums > parseFloat(that.data.mouth.prize_money)) {
          state = 1;
        }
        var pay_money = (nums < parseFloat(that.data.mouth.prize_money) ? (parseFloat(that.data.mouth.prize_money) - nums) : (nums - parseFloat(that.data.mouth.prize_money)));
        console.log(parseFloat(value).toFixed(2));
        that.setData({
          state: state,
          'mouth.duty': num.toFixed(2),
          'mouth.formalities_momey': nums,
          'mouth.prize_src': parseFloat(value).toFixed(2),
          'mouth.pay_money': parseFloat(pay_money),
        })
      }
    } else {
      that.setData({
        state: 0,
        'mouth.duty': '0.00',
        'mouth.prize_src': '0.00',
      })
    }
  },
  blur_input: function (e) {
    var that = this;
    var value = e.detail.value;
    var str_before = value.split(".")[0];
    var str_after = value.split(".")[1];

    if (str_after != undefined) {
      value = value.split(".")[0] + '.' + str_after;
      value = Number(value).toFixed(2);
    } else {
      if (str_before) {
        value = Number(str_before).toFixed(2);
      } else {
        value = '';
      }
    }
    that.setData({
      bounty_value: value,
    })
  },

  // 生成语音口令
  formSubmit: function (e) {
    var that = this;
    var mouth = that.data.mouth;
    var value = e.detail.value;
    var formId = e.detail.formId;
    var currentTab = that.data.currentTab;

    if ((that.data.tempFilePath == undefined || that.data.tempFilePath == '') && currentTab == 0) {
      exhibit('请录音提问');
      return;
    } if (value.text == '' && currentTab == 0) {
      exhibit('请输入答案');
      return;
    }
    if (that.data.bounty_value == '' || that.data.bounty_value == 0) {
      exhibit('请输入赏金');
      return;
    }
    if (that.data.bounty_value < 1) {
      // exhibit('赏金小于1元');
      // return;
    } if (value.prize_num == '' || value.prize_num == 0) {
      exhibit('请输入数量');
      return;
    }


    mouth.text = value.text;
    // mouth.prize_money = that.data.bounty_value;
    mouth.prize_num = value.prize_num;

    // console.log(mouth);
    // wx.showLoading({ title: '加载中', mask: true });


    //微信支付开始
    console.log(that.data.currentTab);
    wx.showLoading({ title: 'loading', mask: true })            
    if (that.data.currentTab == 0) {
      console.log('猜对有钱--进入支付');
      // 猜对有钱
      uploadTask();
    } else {
      console.log('语音口令--进入支付');
      //语音口令
      voice()
    }

    // 猜对有钱
    function uploadTask() {
      console.log(that.data.switchs);
      console.log((that.data.switchs ? 1 : 0));
      wx.uploadFile({
        url: app.url2 + 'api/WePay', //录音接口
        //url: 'http://red/api/WePay',
        filePath: that.data.tempFilePath,
        header: { "Content-Type": "multipart/form-data" },
        name: "file",
        formData: {
          sign:2,
          text: value.text,//口令
          prize_money: mouth.prize_money,//当前小程序剩余的余额
          prize_src: mouth.prize_src,//用户输入的赏金金额
          duty: mouth.duty,//  duty  服务费
          formalities_momey: mouth.formalities_momey,//加上服务费的总金额
          pay_money: mouth.pay_money,//用户还需要微信支付的余额
          prize_num: value.prize_num,//数量
          openid: wx.getStorageSync('openid'),
          duration: that.data.duration,
          avatarurl: wx.getStorageSync('avatarurl'),
          formId: formId,
          token: wx.getStorageSync('token_md5'),          
          is_share: (that.data.switchs ? 1 : 0),
        },
        success: function (res) {//录音返回结果
        console.log(res.data);
          success_one(res);
        },
        fail: (res) => {
          console.log(res);
        }
      })

      // uploadTask.onProgressUpdate((res) => {
      //   console.log('上传进度', res.progress)
      //   console.log('已经上传的数据长度', res.totalBytesSent)
      //   console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
      // })
    };


    //语音口令
    function voice() {
      console.log(that.data.switchs);
      console.log((that.data.switchs ? 1 : 0));
      wx.request({
        url: app.url2 + 'api/WePay', //录音接口
        //url: 'http://red/api/WePay',
        data: {
          sign: 1,
          text: value.text,//口令
          prize_money: mouth.prize_money,//当前小程序剩余的余额
          prize_src: mouth.prize_src,//用户输入的赏金金额
          duty: mouth.duty,//  duty  服务费
          formalities_momey: mouth.formalities_momey,//加上服务费的总金额
          pay_money: mouth.pay_money,//用户还需要微信支付的余额
          prize_num: value.prize_num,//数量
          duration: that.data.duration,
          formId: formId,
          openid: wx.getStorageSync('openid'),
          avatarurl: wx.getStorageSync('avatarurl'),
          token: wx.getStorageSync('token_md5'),          
          is_share: (that.data.switchs ? 1 : 0),
        },
        header: { "Content-Type": "multipart/form-data" },
        success: function (res) {//录音返回结果
          success_one(res);
        },
        fail: (res) => {
          console.log(res);
        }
      })
    }


    //返回成功时的判断
    function success_one(res) {//录音返回结果
      console.log(res);
      wx.hideLoading();
      //微信支付开始
      if (that.data.currentTab == 0) {
        var gol_ = JSON.parse(res.data);
      } else {
        var gol_ =res.data;
      }
      console.log(gol_);
      // 发现敏感词汇
      if (gol_.status == 0) {
        that.setData({
          shadow: false,
          sensitive: false,//敏感
          sensitive_text: gol_.message
        })
        return;
      }
      if (gol_.pay_type == 0) {//当余额不足以支付时，使用微信钱包支付
        console.log('当余额不足以支付时，使用微信钱包支付');
        wx.requestPayment({
          'appId': gol_.data.appid,
          'timeStamp': gol_.data.timeStamp.toString(),
          'nonceStr': gol_.data.nonceStr,
          'package': gol_.data.package,
          'signType': gol_.data.signType,
          'paySign': gol_.data.paySign,

          'success': function (res) {
            console.log(res);
            console.log('success');
            wx.showToast({
              title: '支付成功',
              icon: 'success',
              duration: 3000
            });
            wx.navigateTo({
              url: '/pages/voice_box/forward/index?code_url=' + gol_.data.code_url + '&pages=' + (that.data.currentTab == 0? 1 : 0 ) + '&id=' + gol_.data.redid,
            })
            //清空设置的口令
            emptied(that);
          },
          'fail': function (res) {
            console.log(res);
            wx.showToast({
              title: '支付失败',
              icon: 'loading',
              duration: 1500
            });
          },
        });
      } else if (gol_.pay_type == 1) {//当余额足够支付时，直接支付
        console.log('余额充足够，直接支付');
        wx.showToast({
          title: '零钱已支付',
          icon: 'success',
          duration: 1500
        });
        setTimeout(function () {
          wx.navigateTo({
            url: '/pages/voice_box/forward/index?code_url=' + gol_.data.code_url + '&id=' + gol_.data.redid,
          })
        }, 1500)
        //清空设置的口令
        emptied(that);
      }
    }

    //提示信息
    function exhibit(text) {
      wx.showToast({
        title: text,
        icon: 'loading',
        duration: 1500,
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    // wx.showLoading({ title: '加载中', mask: true })
    var that = this;
    console.log(wx.getStorageSync('openid'));
    that.setData({ reset: 0,});
    if (wx.getStorageSync('openid') == '') {
      // app.load(that.log_load);
      app.load(that.log_load);
    } else {
      that.log_load();
    }

    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success(res) {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              // wx.startRecord()
              console.log(res);
            }
          })
        }
      }
    })

  },
  // 登录后加载
  log_load: function () {
    app.token_md5();

    wx.showLoading({ title: 'loading', mask: true })        
    var that = this;
    wx.request({
      url: app.url2 + 'api/yue',
      data: {
        openid: wx.getStorageSync('openid'),
        token: wx.getStorageSync('token_md5'),
      },
      header: { 'content-type': 'application/json' },
      success: function (res) {
        console.log(res);
        // var data = res.data;
        // var money_num = '0.00';
        // if (data != '0') {
        //   money_num = Number(data).toFixed(2)
        // }
        that.setData({
          blessing_text: wx.getStorageSync('blessing_text'),
          user_img: wx.getStorageSync('avatarurl'),
          'mouth.prize_money': res.data.money,
          currentTab: (wx.getStorageSync('currentTab') ? wx.getStorageSync('currentTab'):'0'),
        })
        wx.hideLoading();        
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad();
    wx.stopPullDownRefresh();
    emptied(this);
  },
  // onReady: function () {
  //   this.innerAudioContext = wx.createInnerAudioContext();
  // },
})

//清空设置的口令
function emptied(that) {
  wx.setStorageSync('blessing_text', '')
  wx.setStorageSync('currentTab', '')
}
